<template>
  <div>
    <!-- 查询表单 -->
    <div class="check-form-box">
      <el-form
        :inline="true"
        :model="searchModel.data"
        class="demo-form-inline"
      >
        <el-form-item label="创单时间">
          <el-date-picker
            v-model="searchModel.orderTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="订单号">
          <el-input
            v-model.trim="searchModel.orderNo"
            placeholder="请输入订单号"
          />
        </el-form-item>
        <!-- <el-form-item label="渠道">
          <el-select v-model="searchModel.channelType" placeholder="请选择">
            <el-option label="全部" :value="null" />
            <el-option label="能链" value="1" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="类型">
          <el-select v-model="searchModel.userType" placeholder="请选择">
            <el-option label="全部" :value="null" />
            <el-option label="C端用户" value="1" />
            <el-option label="代理用户" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="外部ID">
          <el-input
            v-model.trim="searchModel.userId"
            :formatter="(value) => value.replace(/[^\d]/g, '')"
            placeholder="请输入外部ID"
          />
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input
            v-model.trim="searchModel.wnUserId"
            :formatter="(value) => value.replace(/[^\d]/g, '')"
            placeholder="请输入用户ID"
          />
        </el-form-item>
        <el-form-item label="用户姓名">
          <el-input
            v-model.trim="searchModel.wnUsername"
            placeholder="请输入用户姓名"
          />
        </el-form-item>
        <el-form-item label="车牌号">
          <el-input
            v-model.trim="searchModel.licensePlate"
            placeholder="请输入车牌号"
          />
        </el-form-item>
        <el-form-item label="支付时间">
          <el-date-picker
            v-model="searchModel.payTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="折扣卡批次">
          <el-input
            v-model.trim="searchModel.discountCardRuleId"
            placeholder="请输入折扣卡批次"
          />
        </el-form-item>
        <el-form-item label="折扣卡ID">
          <el-input
            v-model.trim="searchModel.discountCardId"
            placeholder="请输入折扣卡ID"
          />
        </el-form-item>
        <el-form-item label="能链订单状态">
          <el-select
            v-model="searchModel.nlOrderStatus"
            placeholder="请选择状态"
          >
            <el-option
              v-for="item in nlOrderStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="华行通订单状态">
          <el-select
            v-model="searchModel.wnOrderStatus"
            placeholder="请选择状态"
          >
            <el-option
              v-for="item in wnOrderStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="subBtnBox">
        <el-button type="primary" color="#ea5b24" @click="searchOrder()"
          >查询</el-button
        >
      </div>
    </div>

    <!-- 列表 -->
    <div>
      <el-table :data="tableData.data" style="width: 100%">
        <el-table-column
          prop="orderTime"
          :formatter="rejigOrderTime"
          width="160"
          label="创单时间"
        />
        <el-table-column prop="orderNo" width="120" label="订单号" />
        <!-- <el-table-column prop="channelType" label="渠道">
          <template #default="scope">
            {{ scope.row.channelType == 1 ? "能链" : "" }}
          </template>
        </el-table-column> -->
        <el-table-column prop="userType" label="类型">
          <template #default="scope">
            {{ scope.row.userType == 1 ? "C端用户" : "代理用户" }}
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="外部ID" />
        <el-table-column prop="wnUserId" label="华行通ID" />
        <el-table-column prop="phone" width="120" label="手机号码" />
        <el-table-column prop="wnUsername" width="100" label="用户姓名" />
        <!-- <el-table-column prop="licensePlate" width="130" label="车牌号" /> -->
        <el-table-column prop="gasName" width="140" label="油站名称" />
        <el-table-column
          prop="payTime"
          width="160"
          :formatter="rejigPayTime"
          label="支付时间"
        />
        <el-table-column prop="oilNo" label="油号" />
        <el-table-column prop="num" label="加油升数" />
        <el-table-column prop="gunPrice" label="枪价" />
        <el-table-column prop="userRealPrice" label="用户单价" />
        <el-table-column prop="totalOrderAmount" label="订单金额" />
        <el-table-column
          prop="totalUserRealAmount"
          width="110"
          label="用户实付金额"
        />
        <el-table-column
          prop="totalUserDiscountAmount"
          width="130"
          label="用户总优惠金额"
        />
        <el-table-column prop="enterpriseRealPrice" label="企业单价" />
        <el-table-column prop="totalEnterpriseRealAmount" label="企业实扣" />
        <el-table-column
          prop="totalEnterpriseDiscountAmount"
          width="100"
          label="企业总优惠"
        />
        <el-table-column
          prop="discountCardRuleId"
          width="100"
          label="折扣卡批次"
        />
        <el-table-column prop="discountCardId" label="折扣卡ID" />
        <el-table-column prop="nlOrderStatus" width="110" label="能链订单状态"
          ><template #default="scope">
            {{ judgeNlOrderStatus(scope.row.nlOrderStatus) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="wnOrderStatus"
          width="110"
          :formatter="judgeWnOrderStatus"
          label="华行通订单状态"
        />
        <el-table-column fixed="right" width="150" label="操作">
          <template v-slot:default="scope">
            <div class="div-cell">
              <el-button
                link
                type="primary"
                size="small"
                @click="refundDialog(scope.row)"
                v-if="
                  (scope.row.wnOrderStatus == 2 ||
                    scope.row.wnOrderStatus == 6) &&
                  pinia.isShow[179]
                "
                >申请退款</el-button
              >
              <el-button
                link
                type="primary"
                size="small"
                @click="showDetails(scope.row)"
                v-if="pinia.isShow[180]"
                >查看详情</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页插件 -->
      <div style="text-align: center">
        <el-pagination
          :total="totalNum"
          @current-change="handleCurrentChange"
          background
          :page-size="size"
          layout="prev, pager, next, total"
          :current-page="page"
        />
      </div>
    </div>

    <!-- 详情dialog -->
    <el-dialog
      v-model="detaildDialogVisible"
      title="能链订单详情"
      center="true"
      modal="true"
      width="500px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item
          label="能链订单状态"
          label-align="right"
          label-class-name="labelCss"
        >
          {{ judgeNlOrderStatus(detailModel.orderStatus) }}
        </el-descriptions-item>
        <el-descriptions-item label="车牌号" label-align="right">
          {{ detailModel.licensePlate }}
        </el-descriptions-item>
        <el-descriptions-item label="订单金额" label-align="right">
          {{ detailModel.totalOrderAmount }}
        </el-descriptions-item>
        <el-descriptions-item label="用户实际支付金额" label-align="right">
          {{ detailModel.totalUserRealAmount }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 退款dialog -->
    <el-dialog
      v-model="refundDialogVisible"
      title="加油退款申请"
      center="true"
      modal="true"
      width="500px"
    >
      <el-form :model="refundParam" label-width="100" label-position="right">
        <el-form-item label="退款原因:" prop="refundReason">
          <el-select v-model="refundParam.refundReason" placeholder="请选择">
            <el-option label="加错站了" value="加错站了" />
            <el-option label="不想加了" value="不想加了" />
            <el-option label="加油站拒绝加油" value="加油站拒绝加油" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="退款备注:" prop="refundRemark">
          <el-input
            v-model.trim="refundParam.refundRemark"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="refundReq()" color="#ea5b24"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import {
  findRefuelOrderApi,
  refundRefuelOrderApi,
  findRefuelOrderDetailApi,
} from "../../../api/index";
import { formatDateTime } from "../../../utils/formatDateTime";
import { usePermissStore } from "../../../store/permiss";
const pinia = usePermissStore();

// 分页列表数据
let tableData: any = reactive([]);
const totalNum = ref(0);
const page = ref(1);
const size = 8;

// 控制详情组件显示
const detaildDialogVisible = ref(false);

// 退款dialog控制
const refundDialogVisible = ref(false);
// 退款参数
const refundParam = reactive({
  mainOrderId: null,
  orderNo: null,
  refundReason: null,
  refundRemark: null,
});

// 搜索模型
const searchModel: any = reactive({
  channelType: null,
  discountCardId: null,
  discountCardRuleId: null,
  licensePlate: null,
  orderNo: null,
  userId: null,
  userType: null,
  wnUserId: null,
  wnUsername: null,
  nlOrderStatus: null,
  wnOrderStatus: null,

  orderTime: null,
  startOrderTime: null,
  endOrderTime: null,
  payTime: null,
  startPayTime: null,
  endPayTime: null,

  page: page,
  size: size,
});

// 广告详情数据模型
let detailModel: any = reactive({
  orderStatus: null,
  licensePlate: null,
  totalOrderAmount: null,
  totalUserRealAmount: null,
});

// 翻页
let flipData = reactive({
  page: page,
  size: size,
});
const handleCurrentChange = (val: number) => {
  page.value = val;
  flipData.page = page.value;
  findOrder(flipData);
};

// 能链订单状态枚举
const nlOrderStatusOptions: any = reactive([
  { value: null, label: "全部" },
  { value: "0", label: "待支付" },
  { value: "1", label: "已支付" },
  { value: "2", label: "退款中" },
  { value: "4", label: "订单取消" },
  { value: "5", label: "已退款" },
  { value: "7", label: "退款失败" },
]);

// 华行通订单状态枚举
const wnOrderStatusOptions: any = reactive([
  { value: null, label: "全部" },
  { value: 1, label: "未支付" },
  { value: 2, label: "已支付" },
  { value: 4, label: "退款中" },
  { value: 5, label: "退款成功" },
  { value: 6, label: "退款失败" },
  { value: 7, label: "支付中" },
  { value: 8, label: "支付失败" },
  { value: 9, label: "已取消" },
]);

// 判断能链状态显示
const judgeNlOrderStatus = (item) => {
  switch (item) {
    case 0:
      return "待支付";
    case 1:
      return "已支付";
    case 2:
      return "退款中";
    case 4:
      return "订单取消";
    case 5:
      return "已退款";
    case 7:
      return "退款失败";
    case 100:
      return "其他";
    default:
      return "";
  }
};

// 判断华行通状态显示
const judgeWnOrderStatus = (row) => {
  switch (row.wnOrderStatus) {
    case 1:
      return "未支付";
    case 2:
      return "已支付";
    case 4:
      return "退款中";
    case 5:
      return "退款成功";
    case 6:
      return "退款失败";
    case 7:
      return "支付中";
    case 8:
      return "支付失败";
    case 9:
      return "已取消";
    default:
      return "";
  }
};

//处理创单时间格式
const rejigOrderTime = (row) => {
  let strTime = "";
  row.orderTime == null ? "" : (strTime = row.orderTime.replace(/T/g, " "));
  return strTime;
};

//处理创单时间格式
const rejigPayTime = (row) => {
  let strTime = "";
  row.payTime == null ? "" : (strTime = row.payTime.replace(/T/g, " "));
  return strTime;
};

// 搜索加油订单
const searchOrder = () => {
  page.value = 1;
  if (searchModel.orderTime) {
    searchModel.startOrderTime = formatDateTime(searchModel.orderTime[0]);
    searchModel.endOrderTime = formatDateTime(searchModel.orderTime[1]).replace(
      "00:00:00",
      "23:59:59"
    );
  } else {
    searchModel.startOrderTime = null;
    searchModel.endOrderTime = null;
  }
  if (searchModel.payTime) {
    searchModel.startPayTime = formatDateTime(searchModel.payTime[0]);
    searchModel.endPayTime = formatDateTime(searchModel.payTime[1]).replace(
      "00:00:00",
      "23:59:59"
    );
  } else {
    searchModel.startPayTime = null;
    searchModel.endPayTime = null;
  }
  searchParmSearch();
  findOrder(searchModel);
  flipData = JSON.parse(JSON.stringify(searchModel));
};

// 查询加油订单
const findOrder = (searchModel) => {
  findRefuelOrderApi(searchModel).then((res) => {
    if (res.data.code === 2000) {
      tableData.data = res.data.data.data;
      totalNum.value = res.data.data.total;
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 搜索参数检查
const searchParmSearch = () => {
  Object.keys(searchModel).forEach((key) => {
    if (!searchModel[key]) {
      searchModel[key] = null;
    }
  });
};

// 展示详情
const showDetails = (item) => {
  detaildDialogVisible.value = true;
  findDetaild(item.orderNo);
};

// 查询详情信息
const findDetaild = (orderNo) => {
  findRefuelOrderDetailApi(orderNo).then((res) => {
    if (res.data.code === 2000) {
      const detailData = res.data.data;
      detailModel.orderStatus = detailData.orderStatus;
      detailModel.licensePlate = detailData.licensePlate;
      detailModel.totalOrderAmount = detailData.totalOrderAmount;
      detailModel.totalUserRealAmount = detailData.totalUserRealAmount;
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 弹出退款dialog
const refundDialog = (row) => {
  Object.keys(refundParam).forEach((key) => (refundParam[key] = null));
  refundParam.mainOrderId = row.orderSummaryId;
  refundParam.orderNo = row.orderNo;
  refundDialogVisible.value = true;
};

// 退款申请
const refundReq = () => {
  if (!refundParam.refundReason) {
    ElMessage.error("请选择退款原因.");
    return;
  }
  refundRefuelOrderApi(refundParam).then((res) => {
    if (res.data.code === 2000) {
      findOrder(searchModel);
      ElMessage({
        message: "申请成功.",
        type: "success",
      });
      refundDialogVisible.value = false;
    } else {
      switch (res.data.code) {
        case 5008:
          ElMessage.error("申请失败:请输入退款金额.");
          break;
        default:
          ElMessage.error("申请失败.");
          break;
      }
    }
  });
};

onMounted(() => {
  findOrder(searchModel);
});
</script>
<style scoped>
:deep(.demo-form-inline) {
  display: grid;
  justify-items: stretch;
  grid-template-columns: repeat(auto-fill, 25%);
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-form-item) {
  width: 90%;
}

.item__txt {
  box-sizing: border-box;
  line-height: 24px;
  padding: 0 9px;
}

.subBtnBox {
  width: 100%;
  margin-bottom: 20px;
  display: block;
  text-align: center;
}

:deep(.labelCss) {
  width: 140px;
}
</style>
